function json2queryString(json) {
  let ret = '?'
  for (let p in json) {
    ret += p + '='
    ret += encodeURIComponent(json[p]) + '&'
  }
  return ret.slice(0, -1)
}

const ERROR_NUM = 10

class Request {
  constructor(props) {
    this.baseURL = props.baseURL
    this.withBaseURL = props.withBaseURL
    this.header = props.header || { 'content-type': 'application/json' }
    this.failedCnt = 0
  }
  get(url, data) {
    return this.request('GET', url, data)
  }
  post(url, data) {
    return this.request('POST', url, data)
  }
  put(url, data) {
    return this.request('PUT', url, data)
  }
  del(url, data) {
    return this.request('DELETE', url, data)
  }
  fail(method, url, data, resolve, reject) {
    return () => {
      if (this.failedCnt >= ERROR_NUM) {
        if (this.offlinePromptNode) {
          this.offlinePromptNode.active = true
        }
        reject({
          msg: "请求失败!",
          url: this.withBaseURL ? this.baseURL + url : url,
          method,
          data
        })
      } else {
        this.failedCnt++
        this.sendRealRequest(method, url, data, resolve, reject)
      }

    }
  }
  sendRealRequest(method, url, data, resolve, reject) {
    try {
      wx.request({
        url: this.withBaseURL ? this.baseURL + url : url,
        method,
        data,
        header: this.header,
        success(res) {
          this.failedCnt = 0
          resolve(res)
        },
        fail: this.fail(method, url, data, resolve, reject)
      })
    } catch (err) {

      let xhr = new XMLHttpRequest()

      url = this.withBaseURL ? this.baseURL + url : url
      if (method === "GET") {
        url += json2queryString(data)
      }
      xhr.onreadystatechange = () => {

        if (xhr.readyState == XMLHttpRequest.DONE) {
          var response = xhr.responseText;
          let res = null
          if (response) {
            res = JSON.parse(response)
          }
          if (xhr.status >= 200 && xhr.status < 400) {
            let ret = {
              data: res,
              errMsg: 'request:ok',
              header: 'Content-Type: "application/json; charset=utf-8"',
              statusCode: 200,
            }
            this.failedCnt = 0
            resolve(ret)
          } else {
            if (this.failedCnt >= ERROR_NUM) {
              if (this.offlinePromptNode) {
                this.offlinePromptNode.active = true
              }
              reject({
                msg: res,
                url,
                method,
                data
              })
            } else {
              this.failedCnt++
              this.sendRealRequest(method, url, data, resolve, reject)
            }
          }
        }
      }

      xhr.open(method, url, true)
      xhr.setRequestHeader('Content-type', this.header['content-type'])
      if (method === 'GET') {
        xhr.send()
      } else {
        xhr.send(JSON.stringify(data));
      }
    }
  }
  request(method, url, data) {
    if (!data) {
      data = {}
    }

    if (this.si) {
      data.si = this.si
    }
    return new Promise((resolve, reject) => {
      this.sendRealRequest(method, url, data, resolve, reject)
    })
  }
}

export default new Request({
  // baseURL: 'http://localhost:3000',
  // baseURL: 'http://116.196.104.146:3000',
  baseURL: 'https://paperrestaurant.illusionorb.com:8081',
  withBaseURL: true
})
